"""
查询正常的节点个数。
如果集群共5个节点，则正常返回5。返回01234均异常。
"""

import requests
import json
import re

def get_h3c_cluster_health_data():
    # 拼接成登陆url
    base_url = "http://地址/"
    request_url = "api/v1/auth/login"
    url = base_url + request_url

    # 登陆用户名、密码
    data = {"username":"xx","password":"xx"}

    # 登录请求
    res = requests.post(url=url,data=json.dumps(data),headers={'content-type':"application/json"})

    # 获取响应头信息
    set_cookie=res.headers.get('Set-Cookie')
    text_set_cookie=re.split('[;,=\']',set_cookie)

    # 从响应头信息中提取后面访问需要的cookie_value和x_xsrf_token_value
    xsrf_token_value=text_set_cookie[1].strip()

    cookie_value = 'calamari_sessionid=' + text_set_cookie[12] + ';' + 'XSRF-TOKEN=' + xsrf_token_value

    # 获取集群ID
    cluster_id_api_url = "/api/v3/plat/cluster"
    cluster_id_url = base_url + cluster_id_api_url
    cluster_res = requests.get(
            url=cluster_id_url,
            headers={
              'content-type':"application/json",
              'X-XSRF-TOKEN':xsrf_token_value,
              'Cookie':cookie_value,
            })

    cluster_data = cluster_res.json()
    cluster_id = cluster_data['data']['id']

    # 生成查询URL
    cluster_health_url_1 = "/api/v3/onestor/"
    cluster_health_url_2 = "/plat/cluster/health"
    cluster_health_url = base_url + cluster_health_url_1 + cluster_id + cluster_health_url_2

    # 发送GET请求，得到返回数据
    cluster_health_res = requests.get(
            url= cluster_health_url,
            headers={
              'content-type':"application/json",
              'X-XSRF-TOKEN':xsrf_token_value,
              'Cookie':cookie_value,
            })
    cluster_health_data = cluster_health_res.json()
    # print(cluster_health_data['data'])
    health_node_num = cluster_health_data['data']['mon']['ok']['count']

    # logout登出
    logout_api_url = "/api/v1/auth/logout"
    logout_url = base_url + logout_api_url
    logout_res = requests.get(
            url= logout_url,
            headers={
              'content-type':"application/json",
              'X-XSRF-TOKEN':xsrf_token_value,
              'Cookie':cookie_value,
            })
    return health_node_num


if __name__ == '__main__':
    health_node_num = get_h3c_cluster_health_data()
    print(health_node_num)
